import express from 'express';
import { spawn } from 'child_process';
import { randomUUID } from 'crypto';

const app = express();
const port = 3100;
const liveAddress = '192.168.124.144'; // 直播服务器的地址，这里就是服务器的ip地址
const livePort = 1935; // 推流端口
const liveFlvPort = 8000; // 拉流端口

// 允许跨域
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    next();
});

app.use(express.static('.'));

// 保存每个直播的 ffmpeg 进程
const liveProcesses = {};

app.get('/start-live', (req, res) => {
    const streamKey = randomUUID();
    const rtmpUrl = `rtmp://${liveAddress}:${livePort}/live/${streamKey}`;
    const flvUrl = `http://${liveAddress}:${liveFlvPort}/live/${streamKey}.flv`;

    // 下面的功能是使用ffmpeg采集桌面，并进行推流。可以根据自己的需求修改参数
    const ffmpegArgs = [
        '-f', 'gdigrab', '-i', 'desktop',
        '-f', 'lavfi', '-i', 'anullsrc',
        '-vcodec', 'libx264', '-pix_fmt', 'yuv420p',
        '-preset', 'veryfast', '-tune', 'zerolatency',
        '-acodec', 'aac', '-ar', '44100', '-ac', '2',
        '-f', 'flv', rtmpUrl
    ];
    // 用 spawn 启动 ffmpeg
    const ffmpegProcess = spawn('ffmpeg', ffmpegArgs, { stdio: 'ignore' });
    liveProcesses[streamKey] = ffmpegProcess;
    res.json({
        streamKey,
        rtmpUrl,
        flvUrl
    });
});

// 关闭直播接口
app.get('/stop-live', (req, res) => {
    const { streamKey } = req.query;
    const proc = liveProcesses[streamKey];
    if (proc) {
        proc.kill();
        delete liveProcesses[streamKey];
        res.json({ success: true, message: '直播已关闭' });
    } else {
        res.json({ success: false, message: '未找到对应的直播进程' });
    }
});

app.listen(port, () => {
    console.log(`Live control server running at http://localhost:${port}`);
}); 